/* MarkusCrawler
 *
 * Copyright (C) 2011 by Markus '[mackan]' Hyttinen <mackanhyttinen@gmail.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 */


package me.crawler;

import java.io.ByteArrayInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class CrawlerHTMLDumpThread extends Thread {
	
	protected CrawlerQueue queue;
	protected String dbUrl;
	protected String userName;
	protected String password;
	protected CrawlerDBManager dbm;
	
	private final String INSERT_ITEM = "INSERT INTO HTML_PAGE("
        + "PAGE_ID,"
        + "URL,"
        + "DATE_CRAWLED,"
        + "PARENT,"
        + "DEPTH,"
        + "CONTENT)"
        + "VALUES(?,?,?,?,?,?)";
	
	
	
	public CrawlerHTMLDumpThread (CrawlerQueue queue ,String dbUrl ,String userName , String password){
		this.dbUrl = dbUrl;
		this.queue = queue;
		this.password = password;
		this.dbUrl = dbUrl;
		this.userName = userName;
	}
	
	
	
	public void setController(CrawlerDBManager dbm){
		
		this.dbm = dbm;
		
	}
	
	public void run(){
		
		Connection con = null;

		try{

			con = DriverManager.getConnection(dbUrl+"/CRAWLER", userName, password);

			while(!queue.isEmpty()){
				CrawlerHTMLPage p = queue.pop();
				PreparedStatement ps = con.prepareStatement(INSERT_ITEM);

				ps.setInt(1, p.getId());
				ps.setString(2, p.getUrl().toString());
				ps.setTimestamp(3, p.dateCrawled);
				ps.setInt(4, p.getParentId());
				ps.setInt(5, p.getDepth());
				ps.setBlob(6, new ByteArrayInputStream(p.getContent()));
				ps.execute();	
			}

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if (con != null) {
				try { con.close(); }
				catch (SQLException e) {
					
				}
			}
			dbm.threadFinished();
		}
	}
		
		
		
		
	}


